'''
给你一个由 n 个整数组成的数组 nums ，和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] ：

0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。

 

示例 1：

输入：nums = [1,0,-1,0,-2,2], target = 0
输出：[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2：

输入：nums = [2,2,2,2,2], target = 8
输出：[[2,2,2,2]]

'''
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        if len(nums) < 4:
            return []
        nums = sorted(nums)
        rl = []
        cur = 0
        while cur < len(nums) - 3:
            two = cur + 1
            while two < len(nums) - 2:
                left, right = two + 1, len(nums) - 1
                while left < right:
                    if nums[cur] + nums[two] + nums[left] + nums[right] == target:
                        rl.append([nums[cur], nums[two], nums[left], nums[right]])
                        while nums[left] == nums[left + 1] and left < right - 1:
                            left += 1
                        left += 1
                        while nums[right] == nums[right - 1] and right > left + 1:
                            right -= 1
                        right -= 1
                    elif nums[cur] + nums[two] + nums[left] + nums[right] > target:
                        while nums[right] == nums[right - 1] and right > left + 1:
                            right -= 1
                        right -= 1
                    elif nums[cur] + nums[two] + nums[left] + nums[right] < target:
                        while nums[left] == nums[left + 1] and left < right - 1:
                            left += 1
                        left += 1
                while nums[two] == nums[two + 1] and two < len(nums) - 2:
                    two += 1
                two += 1
            while nums[cur] == nums[cur + 1] and cur <len(nums) - 3:
                cur += 1
            cur += 1
        return rl